package com.dubbo.protocol.http;

import com.dubbo.protocol.Client;
import com.dubbo.protocol.bean.Invocation;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient implements Client
{

    @Override
    public Object send(URL url, Invocation invocation)
    {
        try
        {
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            //初始化输出流，网络连接输出/文件输出等
            ObjectOutputStream oos= new ObjectOutputStream(connection.getOutputStream());
            oos.writeObject(invocation);
            oos.flush();
//            oos.close();

            //获取返回结果
            InputStream is = connection.getInputStream();

            ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());
            Object result = ois.readObject();
            ois.close();
            System.out.println("httpClient get return result:" + result);
            return result;

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object send(Invocation invocation)
    {
        try
        {
            URL url = new URL("http", "localhost", 8080, "/");
            return send(url, invocation);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception
    {
        URL url = new URL("http","localhost", 8080, "/");

        Invocation ivc = new Invocation();
        ivc.setInterfaceName("com.dubbo.service.UserService");
        ivc.setMethodName("findList");
        ivc.setParamsClass(new Class[]{});
        ivc.setParamsValue(new Object[]{});

        new HttpClient().send(url, ivc);
    }
}
